// var maxProfit = function (prices) {
//     let profit = [];
//     let len = prices.length;
//     for (let i = 1; i < len; i++) {
//         profit.push(Math.max(0, prices[i] - prices[i - 1]));
//     }
//     profit.sort();
//     let n = profit.length;
//     let sum = 0;
//     for (let i = 0; i < n; i++) {
//         sum += profit[i];
//         if (profit[i] == 0) break;
//         if (i == n - 1) return sum;
//     }
//     let max_profit = profit[n - 1] + profit[n - 2];

//     // console.log(profit);

//     return max_profit;
//     // return profit;
// };

var maxProfit = function (prices) {
    if (prices.length <= 1) return 0;
    let min = prices[0];
    let cur_profit = 0;
    let profit = [];
    for (let i = 1; i < prices.length; i++) {
        if (prices[i] < prices[i + 1] && i < prices.length - 1) {
            profit.push(0)
            if (min > prices[i]) min = prices[i];
            continue;
        }
        cur_profit = prices[i] - min;
        if (min > prices[i]) min = prices[i];
        profit.push(Math.max(0, cur_profit))
        if (cur_profit > 0) {
            min = prices[i + 1];
            i++;
        }
    }

    let n = profit.length;
    let sum = 0;
    for (let i = 0; i < n; i++) {
        sum += profit[i];
        if (profit[i] == 0) break;
        if (i == n - 1) return sum;
    }
    if (n == 1) return profit[0];

    profit.sort((a, b) => a - b);
    // console.log(n);
    console.log(profit);
    console.log(profit[n - 1], profit[n - 2]);

    let max_profit = profit[n - 1] + profit[n - 2];

    return max_profit;
};

// prices = [3, 3, 5, 0, 0, 3, 1, 4];
// prices = [1, 2, 3, 4, 5]
// prices = [6, 1, 3, 2, 4, 7]
// prices = [3, 3, 5, 0, 0, 3, 1, 4]
// prices = [14, 9, 10, 12, 4, 8, 1, 16]
prices = [1, 2, 4, 2, 5, 7, 2, 4, 9, 0];

// console.log(maxProfit(prices));
let r = maxProfit(prices);
console.log(r);

